<template>
  <transition name="fade">
    <div class="shelf-title" :class="{'hide-shadow': ifHideShadow}" v-show="shelfTitleVisible">
      <div class="shelf-title-text-wrapper">
        <span class="shelf-title-text">{{title}}</span>
        <span class="shelf-title-sub-text" v-show="isEditMode">{{selectedText}}</span>
      </div>
      <!-- 清除缓存按钮 -->
      <div class="shelf-title-btn-wrapper shelf-title-left" v-if="!showBack && showClear">
        <span class="shelf-title-btn-text" @click="clearCache">{{$t('shelf.clearCache')}}</span>
      </div>
      <!-- 编辑取消按钮 -->
      <div class="shelf-title-btn-wrapper shelf-title-right" v-if="showEdit">
        <span class="shelf-title-btn-text" @click="onEditClick">{{isEditMode ? $t('shelf.cancel') : $t('shelf.edit')}}</span>
      </div>
      <!-- 返回按钮 -->
      <div class="shelf-title-btn-wrapper shelf-title-left" v-if="showBack">
        <span class="icon-back" @click="back"></span>
      </div>
      <!-- 修改分组按钮，有可能排左有可能排右 -->
      <div class="shelf-title-btn-wrapper"
           :class="{'shelf-title-left': changeGroupLeft, 'shelf-title-right': changeGroupRight}" @click="changeGroup"
           v-if="showChangeGroup">
        <span class="shelf-title-btn-text">{{$t('shelf.editGroup')}}</span>
      </div>
    </div>
  </transition>
</template>

<script>
  import { storeShelfMixin } from '../../utils/mixin'
  import { removeLocalStorage, saveBookShelf } from '../../utils/localStorage'
  import { clearLocalForage } from '../../utils/localForage'
  import { deleteGroup, shelf } from '../../api/store'
  import { appendAddToShelf } from '../../utils/store'

  export default {
    mixins: [storeShelfMixin],
    props: {
      title: String
    },
    data() {
      return {
        ifHideShadow: true
      }
    },
    computed: {
      // 判断分组列表是否为空，用于按钮显示,这是为空
      emptyCategory() {
        return this.shelfCategory.list.length === 0
      },
      // 编辑
      showEdit() {
        return this.currentType === 1 || (this.currentType === 2 && !this.emptyCategory)
      },
      // 清除缓存
      showClear() {
        return this.currentType === 1
      },
      showBack() {
        return this.currentType === 2 && !this.isEditMode
      },
      // 修改分组
      showChangeGroup() {
        return (this.currentType === 2 && this.isEditMode) || (this.currentType === 2 && this.emptyCategory)
      },
      changeGroupLeft() {
        return !this.emptyCategory && this.isEditMode
      },
      changeGroupRight() {
        return this.emptyCategory
      },
      selectedText() {
        const selectedNumber = this.shelfSelected ? this.shelfSelected.length : 0
        return selectedNumber <= 0 ? this.$t('shelf.selectBook') : (selectedNumber === 1 ? this.$t('shelf.haveSelectedBook').replace('$1', selectedNumber) : this.$t('shelf.haveSelectedBooks').replace('$1', selectedNumber))
      },
      // 调一个取消按钮
      popupCancelBtn() {
        return this.createPopupBtn(this.$t('shelf.cancel'), () => {
          this.hidePopup()
        })
      }
    },
    watch: {
      offsetY(offsetY) {
        if (offsetY > 0) {
          this.ifHideShadow = false
        } else {
          this.ifHideShadow = true
        }
      }
    },
    methods: {
      onComplete() {
        // 隐藏popup
        this.hidePopup()
        // 删除分组
        this.setShelfList(this.shelfList.filter(book => book.id !== this.shelfCategory.id)).then(() => {
          // 删除完后更新书架的数据
          saveBookShelf(this.shelfList)
          this.$router.go(-1)
          this.setIsEditMode(false)
        })
      },
      //  确定删除分组调用的方法.第一件事是将分组内的所有书籍般到默认分组，第二件事是
      deleteGroup() {
        // todo:调用删除分组API
          // 设置删除分组内的书籍全部置为选中状态
          // this.setShelfSelected(this.shelfCategory.list)
          // // 调用移出分组的方法
          // this.moveOutOfGroup(this.shelfCategory)
          // 调用删除分组API
          deleteGroup(this.shelfCategory.groupId).then(res => {
            console.log('删除分组API返回', res)
          })
          // 更新书架列表
          shelf().then(response => {
            if (response && response.result) {
              console.log('书架列表', response.result)
              const list = appendAddToShelf(response.result)
              // 存到localForage中
              saveBookShelf(list)
              // 将书架列表存到vuex里，return一个promise对象出去
              this.setShelfList(list)
              // 更新分组下书籍列表
              if (this.currentType === 2) {
                this.getCategoryList(this.shelfCategory.groupName)
              }
            }
          })
          this.$router.go(-1)
          this.setIsEditMode(false)
      },
      // 修改分组名称方法
      changeGroupName() {
        this.hidePopup()
        this.dialog({
          // 一打开直接进入编辑分组名称这个对话框
          showNewGroup: true,
          // 传入分组名
          groupName: this.shelfCategory.groupName
        }).show()
        // 然后到ShelfGroupDialog组件修改新建分组的方法
      },
      // 隐藏popup弹窗
      hidePopup() {
        this.popupMenu.hide()
      },
      // 创建按钮对象方法。text按钮的文本，onClick事件，返回一个按钮的对象
      createPopupBtn(text, onClick, type = 'normal') {
        return {
          text: text,
          type: type,
          click: onClick
        }
      },
      // 删除分组的方法，再显示一个popup
      showDeleteGroup() {
        this.hidePopup()
        setTimeout(() => {
          this.popupMenu = this.popup({
            title: this.$t('shelf.deleteGroupTitle'),
            btn: [
              // createPopupBtn()方法快速创建按钮对象
              this.createPopupBtn(this.$t('shelf.confirm'), () => {
                // 确定删除分组调用的方法
                this.deleteGroup()
              }, 'danger'),
              this.popupCancelBtn
            ]
          }).show()
        }, 200)
      },
      // 点击修改分组的方法
      changeGroup() {
        console.log('进入修改分组方法')
        this.popupMenu = this.popup({
          btn: [
            // createPopupBtn()方法快速创建按钮对象
            this.createPopupBtn(this.$t('shelf.editGroupName'), () => {
              // 编辑分组名称方法
              this.changeGroupName()
            }),
            this.createPopupBtn(this.$t('shelf.deleteGroup'), () => {
              // 删除分组的方法，再显示一个分组
              this.showDeleteGroup()
            }, 'danger'),
            // 调一个取消按钮，定义成了计算属性
            this.popupCancelBtn
          ]
        }).show()
      },
      // 返回按钮
      back() {
        this.$router.go(-1)
        this.setIsEditMode(false)
      },
      // 编辑状态切换的点击事件，点完取消的时候
      onEditClick() {
        if (!this.isEditMode) {
          // 将shelfSelected清空
          this.shelfSelected.forEach(item => {
            item.selected = false
          })
          this.setShelfSelected([])
          // 将shelfList的选中状态去掉
          this.shelfList.forEach(item => {
            item.selected = false
            if (item.itemList) {
              item.itemList.forEach(subItem => {
                subItem.selected = false
              })
            }
          })
        }
        this.setIsEditMode(!this.isEditMode)
      },
      // 清除缓存方法
      clearCache() {
        console.log('清除缓存，clearCache()')
        // 将localStorge里面的书籍清空
        // 删除书架列表信息
        removeLocalStorage('shelf')
        // removeLocalStorage(`${book.categoryText}/${book.fileName}-info`)
        removeLocalStorage('fontFamily')
        removeLocalStorage('locale')
        removeLocalStorage('location')
        removeLocalStorage('bookmark')
        removeLocalStorage('time')
        removeLocalStorage('progress')
        removeLocalStorage('navigation')
        removeLocalStorage('metadata')
        removeLocalStorage('cover')
        removeLocalStorage('theme')
        removeLocalStorage('fontSize')
        // 清除缓存的电子书
        console.log('清除缓存的电子书')
        // 将localForage里面的数据清空
        clearLocalForage()
        // 将vuex里的数据清空
        this.setShelfList([])
        this.setShelfSelected([])
        // 重新获取书架列表接口api，mixin方法
        this.getShelfList()
        // this.simpleToast(this.$t('shelf.clearCacheSuccess'))
        this.$emit('showMyToast', this.$t('shelf.clearCacheSuccess'))
      }
    }
  }
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
  @import "../../assets/styles/global";
  .shelf-title {
    z-index: 130;
    position: relative;
    width: 100%;
    height: px2rem(84);// 42
    background: white;
    box-shadow: 0 px2rem(2) px2rem(2) 0 rgba(0, 0, 0, .1);
    &.hide-shadow {
      box-shadow: none;
    }
    .shelf-title-text-wrapper {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: px2rem(84);//42
      @include columnCenter;
      .shelf-title-text {
        font-size: px2rem(38);//16
        line-height: px2rem(40);//20
        font-weight: bold;
        color: #333;
      }
      .shelf-title-sub-text {
        font-size: px2rem(20);// 10
        color: #333;
      }
    }
    .shelf-title-btn-wrapper {
      position: absolute;
      top: 0;
      box-sizing: border-box;
      height: 100%;
      @include center;
      .shelf-title-btn-text {
        font-size: px2rem(36);// 14
        color: #666;
      }
      // 返回按钮的样式
      .icon-back {
        font-size: px2rem(40);//20
        color: #666;
      }
      &.shelf-title-left {
        left: 0;
        padding-left: px2rem(30);//15
      }
      &.shelf-title-right {
        right: 0;
        padding-right: px2rem(30);// 15
      }
    }
  }
</style>
